package com.general.app.xtgl.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.general.common.action.BaseAction;
import com.general.common.security.entity.User;
import com.general.utils.base.Constant;
import com.general.utils.base.IPRequest;
import com.general.utils.base.StringUtil;
import com.general.utils.encrypt.Encrypt;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.util.ValueStack;

/**
 * 登录认证模块
 * 
 * @author Penghui.Qu
 * 
 */

public class CopyOfLoginAction extends BaseAction implements ModelDriven<User> {

	private static final long serialVersionUID = -1110264619149651296L;
	private Logger log = LoggerFactory.getLogger(CopyOfLoginAction.class);

    public static final String SUCCESS_PHONE = "successPhone";
	private User user = new User();

	//SecurityUtils.getSubject().getPrincipal(); 取User对象
	
	//@RequiresPermissions("user:edit")
	//@RequiresRoles(value = { "Admin", "User" }, logical = Logical.OR)
	//验证码session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY)
	
	
	/**
	 * 登录认证
	 * 
	 * @return
	 */
	public String login() {

		//构建当前操作用户
		//WebSubject.Builder b = new WebSubject.Builder(request, response);
		//Subject subject = b.buildSubject();
		Subject subject = SecurityUtils.getSubject();
		
		// 判断当前用户是否认证过
		if (subject.isAuthenticated()) {
			HttpSession session = getSession();
			String usertype  = (String)session.getAttribute("userType");		// 判断是否是手机端（true:手机端）/false:PC端）
			String isMobileDevice = (String)session.getAttribute("isMobileDevice");
			
			ValueStack vs = getValueStack();		
			vs.set("userType", usertype);		
			vs.set("isMobileDevice", isMobileDevice);
			User user = getCurrentUser();
			vs.set("username", user.getUsername());
			
			//问卷回答者并且手机访问，则跳转到手机端
//			if(Constant.USER_TYPE_ANSWER.equals(usertype) && "true".equals(isMobileDevice)){
//				return SUCCESS_PHONE;
//			}
			//return SUCCESS;
			return SUCCESS_PHONE;
		}

		// 判断是否是手机端（true:手机端）/false:PC端）
		boolean isMobileDevice = HttpRequestDeviceUtils.isMobileDevice(getRequest());
		
		//答卷者
		if( !StringUtil.isEmpty(user.getType()) && "answer".equals(user.getType())&& !StringUtil.isEmpty(user.getUsername())){
			
			UsernamePasswordToken token = new UsernamePasswordToken(
					user.getUsername(), Encrypt.encrypt("0"));
			
			//登录认证
			subject.login(token);			
			HttpSession session = getSession();
			session.setAttribute("userType", Constant.USER_TYPE_ANSWER);
			session.setAttribute("isMobileDevice", isMobileDevice);
			
			ValueStack vs = getValueStack();		
			vs.set("usertype", Constant.USER_TYPE_ANSWER);
			vs.set("isMobileDevice", isMobileDevice);
			User user = getCurrentUser();
			vs.set("username", user.getUsername());
			
			//return SUCCESS;
			return SUCCESS_PHONE;
		}
		
		//用户名或密码为空
		if (StringUtil.isEmpty(user.getPassword()) || StringUtil.isEmpty(user.getUsername())){
			
			return LOGIN;
		}

		UsernamePasswordToken token = new UsernamePasswordToken(
				user.getUsername(), Encrypt.encrypt(user.getPassword()));
		try {
			//登录认证
			token.setRememberMe(true);
			subject.login(token);

			HttpSession session = getSession();
			session.setAttribute("userType", Constant.USER_TYPE_MANAGER);
			ValueStack vs = getValueStack();		
			vs.set("userType", Constant.USER_TYPE_MANAGER);
			User user = getCurrentUser();
			vs.set("username", user.getUsername());

			//return SUCCESS;
			return SUCCESS_PHONE;
		} catch (Exception e) {

			//认证失败
			String errMsg = null;
			
			if (e instanceof UnknownAccountException || e instanceof IncorrectCredentialsException) {
				errMsg = "IP:{},UserName:{},认证失败！";
			} else {
				errMsg = "IP:{},UserName:{},登录异常！";
			}

			HttpServletRequest request = getRequest();
			String ip = IPRequest.getIpAddress(request);
			
			if (log.isDebugEnabled()){
				log.debug(errMsg,ip,user.getUsername());
			}
			token.clear();
			
			getValueStack().set("message", "用户名或密码错误，请重新输入。");
		}
		return LOGIN;
	}


	/**
	 * 登录认证[答卷者]
	 * 
	 * @return
	 */
	public String loginAnswer() {

		//构建当前操作用户
		Subject subject = SecurityUtils.getSubject();
		
		// 判断当前用户是否认证过
		if (subject.isAuthenticated()) {
			return SUCCESS;
		}
		
		//用户名或密码为空
		if (StringUtil.isEmpty(user.getUsername())){
			return LOGIN;
		}

		UsernamePasswordToken token = new UsernamePasswordToken(
				user.getUsername(), Encrypt.encrypt("0"));
		try {
			//登录认证
			//token.setRememberMe(true);
			subject.login(token);
			
			return "successAnswer";
		} catch (Exception e) {

			//认证失败
			String errMsg = null;
			
			if (e instanceof UnknownAccountException || e instanceof IncorrectCredentialsException) {
				errMsg = "IP:{},UserName:{},认证失败！";
			} else {
				errMsg = "IP:{},UserName:{},登录异常！";
			}

			HttpServletRequest request = getRequest();
			String ip = IPRequest.getIpAddress(request);
			
			if (log.isDebugEnabled()){
				log.debug(errMsg,ip,user.getUsername());
			}
			token.clear();
			e.printStackTrace();
		}
		return LOGIN;
	}
	
	/**
	 * 注销
	 * @return
	 */
	public String logout(){
		
		Subject subject = SecurityUtils.getSubject();
		
		subject.logout();
		
		return LOGIN;
	}
	
	/**
	 * 跳转首页
	 * @return 首页
	 */
	public String indexBody(){
		
		return "indexBody";
	}
	
	
	
	
	@Override
	public User getModel() {
		
		return user;
	}
}
